package com.randev.snapcamera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.randev.snap.MainMenuActivity;
import com.randev.snap.R;
import com.randev.snapconfig.Config;


@SuppressLint("HandlerLeak")
public class CameraActivity extends Activity implements SurfaceHolder.Callback, OnTouchListener {

	private SurfaceHolder cameraHolder;
	private SurfaceView surfaceView;
	private Camera deviceCamera;
	private final String TAG = "CameraActivity";
	private List<Size> supportedPreviewSizes;
	private Size bestPreviewSize;
	private boolean previewActive = false;
	private boolean EXTERNAL_STORAGE_AVAILABLE = false;
	private int screenOrientation = 0;
	private String folderId = "";
	private int camOrientation = 0;
	private AlertDialog.Builder alertDialog;
	
	protected static ProgressDialog progressDialog;
	protected static boolean imageSaveRunning = false;
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		progressDialog = new ProgressDialog(this);
		
		setContentView(R.layout.camera);
		
		surfaceView = (SurfaceView) findViewById(R.id.svCamera);
		cameraHolder = surfaceView.getHolder();
		cameraHolder.addCallback(this);
		cameraHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		alertDialog = new AlertDialog.Builder(CameraActivity.this);
		surfaceView.setOnTouchListener(this);
		
		EXTERNAL_STORAGE_AVAILABLE = isExternalStorageWritable();
		
		if (!EXTERNAL_STORAGE_AVAILABLE) {
	    	alertDialog.setTitle(CameraActivity.this.getString(R.string.error));
	    	TextView tViewWarning = new TextView(CameraActivity.this);
	    	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tViewWarning.setHeight(90);
	    	alertDialog.setView(tViewWarning);
	    	tViewWarning.setText(CameraActivity.this.getString(R.string.erorr_sd_card_not_detected));
	    			alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					try {
						Intent MainMenuIntent = new Intent(CameraActivity.this, MainMenuActivity.class);
						finish();
						startActivity(MainMenuIntent);
					} catch (ActivityNotFoundException e) {
						
						Log.w(TAG, "Error starting MainMenu Activity:" + e.toString());
					}
				}
			});
	    	alertDialog.setCancelable(false);
	    	alertDialog.show();
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		imageSaveRunning = savedInstanceState.getBoolean(Config.IMAGE_SAVE_STATUS);
		Log.w(TAG, "BOLEAN isSaveRunning: " + imageSaveRunning);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean(Config.IMAGE_SAVE_STATUS, imageSaveRunning);
		super.onSaveInstanceState(outState);
		Log.w(TAG, "imageSaveRunning" + imageSaveRunning);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (previewActive) {
				deviceCamera.stopPreview();
				previewActive = false;
			} 
			deviceCamera.release();
			
		} catch (Exception e) {
			try {
				deviceCamera.release();
			}catch (Exception ex) {
				Log.w(TAG, "Error releasing camera in Destroy: " + ex.toString());	
			}
			Log.w(TAG, "Error releasing camera in Destroy: " + e.toString());		
		}
		
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		try {
			if (previewActive) {
				deviceCamera.stopPreview();
				previewActive = false;
			} 
			if (progressDialog.isShowing()) { 
				progressDialog.dismiss();
			}
			deviceCamera.release();
			
		} catch (Exception e) {
			try {
				deviceCamera.release();
			}catch (Exception ex) {
				Log.w(TAG, "Error releasing camera in Pause: " + ex.toString());	
			}
			Log.w(TAG, "Error releasing camera in Pause: " + e.toString());		
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			startCamera();
			if (imageSaveRunning) {
				if (!progressDialog.isShowing()) {
					progressDialog.setMessage(CameraActivity.this.getString(R.string.info_saving_image));
					progressDialog.show();
				}
			} else {
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
			}
		} catch (Exception e) {
			Log.w(TAG, "Unable to start camera on resume: " + e.toString());
	    	alertDialog.setTitle(CameraActivity.this.getString(R.string.error));
	    	TextView tViewWarning = new TextView(CameraActivity.this);
	    	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tViewWarning.setHeight(90);
	    	alertDialog.setView(tViewWarning);
	    	tViewWarning.setText(CameraActivity.this.getString(R.string.error_unable_start_camera));
	    			alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					try {
						Intent MainMenuIntent = new Intent(CameraActivity.this, MainMenuActivity.class);
						finish();
						startActivity(MainMenuIntent);
					} catch (ActivityNotFoundException e) {
						
						Log.w(TAG, "Error starting MainMenu Activity:" + e.toString());
					}
				}
			});
	    	alertDialog.setCancelable(false);
	    	alertDialog.show();
		}
		
		
		
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		try {
			if (previewActive) {
				deviceCamera.stopPreview();
			}
			Parameters cameraParameters = deviceCamera.getParameters();
			cameraParameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
			
			double ratio = getBestPreviewRatio(bestPreviewSize.width, bestPreviewSize.height);
			
			Size holderFrameSize = getsurfaceHolderSize(ratio, bestPreviewSize);
			surfaceView.getHolder().getSurfaceFrame().set(0, 0, holderFrameSize.width, holderFrameSize.height);
			deviceCamera.setParameters(cameraParameters);
			surfaceView.requestLayout();
			
			deviceCamera.startPreview();
			previewActive = true;
		} catch (Exception e) {
			Log.w(TAG, "surfaceChanged: " + e.toString());
		}
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			bestPreviewSize = getBestPreviewSize(supportedPreviewSizes);
			android.hardware.Camera.CameraInfo cam = new android.hardware.Camera.CameraInfo();
			android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, cam);
			Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
			screenOrientation = display.getRotation();
			camOrientation = cam.orientation;
			
			int rotation = 0;
			Log.w("Camera Orientation", String.valueOf(camOrientation)+ " " + screenOrientation );
			if (camOrientation == 0) {
				switch (screenOrientation) {
				case 0:
					rotation = camOrientation;
					break;
				case 1:
					rotation = camOrientation;
					break;
				case 2:
					rotation = 180;
					break;
				case 3:
					rotation = 90;
					break;
				}
			} else if (camOrientation == 90) {
				switch (screenOrientation) {
				case 0:
					rotation = camOrientation;
					if (rotation == 360) {
						rotation = 0;
					}
					break;
				case 1:
					rotation = 0;
					break;
				case 3:
					rotation = 180;
					break;
				}
			}

			deviceCamera.setDisplayOrientation(rotation);
			try {
				deviceCamera.setPreviewDisplay(cameraHolder);
			} catch (IOException e) {
				deviceCamera.release();
				Log.w(TAG, "Unable to set camera to holder: "+ e.toString());
			}
			deviceCamera.startPreview();
			previewActive = true;
		} catch (Exception e) {
			Log.w(TAG, "surfaceCreated: " + e.toString());
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		
		
	}
	
	private Size getBestPreviewSize(List<Size> supportedPreviewSizes) {
		Size bestPreviewSize = supportedPreviewSizes.get(0);
		
		for (Size screenSize: supportedPreviewSizes) {
			
			if (screenSize.width * screenSize.height > bestPreviewSize.width  * bestPreviewSize.height) {
				bestPreviewSize = screenSize;
			}
		}
		Log.w(TAG, "Best preview: " + bestPreviewSize.height + " --> " + bestPreviewSize.width);
		return bestPreviewSize;
	}
	
	private double getBestPreviewRatio(int width, int height) {
		double ratio = (double) width / height;
		Log.w(TAG, "ratio: " + ratio);
		return (double) width / height;
	}
	
	@SuppressWarnings("deprecation")
	private Size getsurfaceHolderSize(double ratio, Size previewSize) {
		
		double bestPreviewHeight = bestPreviewSize.height;
		double bestPreviewWidth = bestPreviewSize.width;
		double bestPreviewRatio = 0D;
		Size holderSize = previewSize;
		
		if (bestPreviewHeight > 0) {
			bestPreviewRatio = (double) bestPreviewWidth/bestPreviewHeight;
		}
		
		

		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		double displayHeight = display.getHeight();
		double displayWidth = display.getWidth();
		
		double currentDisplayWidth = displayWidth;
		double currentDisplayHeight = displayHeight;
		
		if (displayWidth > displayHeight) {
			currentDisplayWidth = displayHeight;
			currentDisplayHeight = displayWidth;
		}
		
		double requiredHeight =  currentDisplayWidth/ bestPreviewRatio;
		double requiredWidth = currentDisplayHeight * bestPreviewRatio;
		
		if (requiredWidth >= currentDisplayWidth ) {
			requiredWidth = currentDisplayWidth;
		} else {
			requiredHeight = currentDisplayHeight;
		}
		
		
		if (currentDisplayWidth >= ((double) bestPreviewRatio * currentDisplayHeight)) {
			requiredWidth = currentDisplayWidth;
			requiredHeight = (int) (currentDisplayWidth / (double) bestPreviewRatio);
			Log.w("getsurfaceHolderSize", "1");
		} else {
			requiredWidth = currentDisplayHeight;
			requiredHeight = (int) (currentDisplayHeight * (double) bestPreviewRatio);
		}
		
		double finalScreenHeight = 0D;
		double finalScreenWidth = 0D;
		
		if (requiredWidth > requiredHeight) {
			finalScreenHeight = requiredWidth;
			finalScreenWidth = requiredHeight;
		} else {
			finalScreenHeight = requiredHeight;
			finalScreenWidth = requiredWidth;
		}
		
		holderSize.height = (int) finalScreenHeight;
		holderSize.width = (int) finalScreenWidth;
		
		Log.w(TAG, "required height:" + finalScreenHeight + " required width: " + finalScreenWidth);
		
		return holderSize;
		
	}
	
	private PictureCallback pictureCallback = new PictureCallback() {

	    @Override
	    public void onPictureTaken(byte[] data, Camera camera) {
	    	
	    	

	    	camera.stopPreview();
	    	progressDialog.setMessage(CameraActivity.this.getString(R.string.info_saving_image));
	    	progressDialog.show();
	    	Object[] cameraData = new Object[2];
	    	cameraData[0]  = data;
	    	cameraData[1] = camera;
	    	new ImageSave().execute(cameraData);
	    	
	        
        } 
    };
    
    private File createSaveDirectory(String fileId) {
		
		File childSaveDirectory = null;
		
		String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
		String parent = sdCard + File.separator + "AndroidTest";
		File saveParentDirectory = new File(parent);
		
		if (saveParentDirectory.exists()) {
			String child = parent + File.separator + "Set "+ fileId;
			childSaveDirectory = new File(child);
			if (!childSaveDirectory.exists()) {
				childSaveDirectory.mkdirs();
			}
			
		} else {
			saveParentDirectory.mkdirs();
			String child = parent + File.separator + "Set "+ fileId;
			childSaveDirectory = new File(child);
			if (!childSaveDirectory.exists()) {
				childSaveDirectory.mkdirs();
			}
		}
		
		return childSaveDirectory;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
	        String imagesAvailable = prefs.getString(Config.IMAGES_AVAILABLE, null);
	        String imageCount = prefs.getString(Config.IMAGE_COUNT, null);
	        int imgAvl = Integer.parseInt(imagesAvailable);
	        int imgCount = Integer.parseInt(imageCount);
	        folderId =  prefs.getString("FolderId", null);
	        
	        if (imgAvl == imgCount) {
	        	try {
	        	
		        	if (progressDialog.isShowing()) {
		        		progressDialog.dismiss();
		        	}
					Intent  mainMenuIntent = new Intent(CameraActivity.this, MainMenuActivity.class);
					finish();
					startActivity(mainMenuIntent);
				} catch (ActivityNotFoundException e) {
					Log.w(TAG, "Unable to start mainmenu activity: " + e.toString());
				}
	        } else {
	        	try {
	        		if (progressDialog.isShowing()) {
	        			progressDialog.dismiss();
		        	}
	        	
	        		Bundle bundle = new Bundle();
	        		bundle.putString(Config.FOLDER_ID, folderId);
					Intent  albumDetailsIntent = new Intent(CameraActivity.this, CameraAlbumDetails.class);
					albumDetailsIntent.putExtras(bundle);
					finish();
					startActivity(albumDetailsIntent);
				} catch (ActivityNotFoundException e) {
					Log.w(TAG, "Unable to start albumDetailsIntent activity: " + e.toString());
				}
	        }
	        
	        
	    	
	    	
	    	return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
	
	private boolean isExternalStorageWritable() {
		boolean isMediaAvailable = false;
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	    	isMediaAvailable =  true;
	    }
	    return isMediaAvailable;
	}
	
	private Bitmap rotateBitmap(byte[] data) {
		Bitmap rotatedBitmap = null;
		try {
			BitmapFactory.Options bounds = new BitmapFactory.Options();
	        bounds.inJustDecodeBounds = true;
	        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
	       
	        Matrix matrix = new Matrix();
	       
	        if (camOrientation == 0) {
				switch (screenOrientation) {
				case 0:
					matrix.setRotate(0);
					break;
				case 1:
					matrix.setRotate(270);
					break;
				case 2:
					matrix.setRotate(180);
					break;
				case 3:
					matrix.setRotate(90);
					break;
				}
			} else if (camOrientation == 90) {
				switch (screenOrientation) {
				case 0:
					matrix.setRotate(90);
					break;
				case 1:
					matrix.setRotate(0);
					break;
				case 3:
					matrix.setRotate(180);
					break;
				}
			}
	        
//	        if (screenOrientation == 0) {
//	        	matrix.setRotate(90);
//	        } else if (screenOrientation == 1) {
//	        	matrix.setRotate(0);
//	        } else if (screenOrientation == 3) {
//	        	matrix.setRotate(180);
//	        }

	        rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, false);
		} catch (IllegalArgumentException e) {
			Log.w(TAG, "Illegal Argument while creating bitmap: " + e.toString());
		} catch (OutOfMemoryError e) {
			Log.w(TAG, "out of memory : " + e.toString());
		}
		
		return rotatedBitmap;
	}
	
	private boolean checkImageCount() {
		boolean status = false;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
        String imagesAvailable = prefs.getString("ImagesAvailable", null);
        try {
        	int imgAvl = Integer.parseInt(imagesAvailable);
        	if (imgAvl > 0) {
        		status = true;
        	} else if (imgAvl == 0) {
        		status = false;
	    	}
        } catch (NumberFormatException e) {
        	Log.w(TAG, "Unable to parse number of images left: " + e.toString());
        	status = false;
        }
		return status;
	}
	
	private boolean saveFile(Bitmap rotatedBitmap, String fileName) {
		boolean status = false;
		try {
			FileOutputStream fos;
            fos = new FileOutputStream(fileName);
            rotatedBitmap.compress(Bitmap.CompressFormat.JPEG,70, fos);
            fos.flush();
            fos.close();
            status =  true;
		} catch (FileNotFoundException e) {
			Log.w(TAG, "FileNotFoundException when fileoutputstream " + e.toString());
			status = false;
		} catch (IOException e) {
			Log.w(TAG, "IOException when fileoutputstream " + e.toString());
			status =  false;
		}
		return status;
	}
	
	private class ImageSave extends AsyncTask<Object, Void, String> {

		boolean status = false;
		Camera cam;
		@Override
		protected String doInBackground(Object... params) {
			imageSaveRunning = true;
			byte[] data = (byte[]) params[0];
			cam = (Camera) params[1];
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
	        folderId =  prefs.getString("FolderId", null);
	        String imagesAvailable = prefs.getString("ImagesAvailable", null);
            
            if (EXTERNAL_STORAGE_AVAILABLE) {
            	if (checkImageCount()) {
	            	File saveDirectory = null;
	            	saveDirectory = createSaveDirectory(folderId);
	            	
	            	if (saveDirectory != null) {
	            		Bitmap rotatedBitmap = rotateBitmap(data);
						if (progressDialog.isShowing()) {
							progressDialog.dismiss();
						}
	            			
            			String fileName = saveDirectory.toString() + File.separator + imagesAvailable+".jpeg";
            			status = saveFile(rotatedBitmap, fileName);
            			
            			
	            			
	            	} else {
	            		Log.w(TAG, "Save Directory not created !");
	            	}
	            } else {
		        	alertDialog.setTitle(CameraActivity.this.getString(R.string.alert));
		        	TextView tViewWarning = new TextView(CameraActivity.this);
		        	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
		        	tViewWarning.setHeight(90);
		        	alertDialog.setView(tViewWarning);
		        	tViewWarning.setText(CameraActivity.this.getString(R.string.info_max_images_taken));
				    alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							try {
								try {
									
									if (progressDialog.isShowing()) {
										progressDialog.dismiss();
	    							}
					        		Bundle bundle = new Bundle();
					        		bundle.putString(Config.FOLDER_ID, folderId);
									Intent  albumDetailsIntent = new Intent(CameraActivity.this, CameraAlbumDetails.class);
									albumDetailsIntent.putExtras(bundle);
									finish();
									startActivity(albumDetailsIntent);
								} catch (ActivityNotFoundException e) {
									Log.w(TAG, "Unable to start albumDetailsIntent activity: " + e.toString());
								}
    						} catch (ActivityNotFoundException e) {
    							Log.w(TAG, "Error starting MainMenu Activity:" + e.toString());
    						}
							
						}
					});
		        	alertDialog.setCancelable(false);
		        	alertDialog.show();
		        	
	            }
            } else {
	        	alertDialog.setTitle(CameraActivity.this.getString(R.string.error));
	        	TextView tViewWarning = new TextView(CameraActivity.this);
	        	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
	        	tViewWarning.setHeight(90);
	        	alertDialog.setView(tViewWarning);
	        	tViewWarning.setText(CameraActivity.this.getString(R.string.erorr_sd_card_not_detected));
	        	alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						try {
							Intent MainMenuIntent = new Intent(CameraActivity.this, MainMenuActivity.class);
							finish();
							startActivity(MainMenuIntent);
						} catch (ActivityNotFoundException e) {
							Log.w(TAG, "Error starting MainMenu Activity:" + e.toString());
						}
					}
				});
	        	alertDialog.setCancelable(false);
	        	alertDialog.show();
            }
            
			return String.valueOf(status);
			
			
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
	        folderId =  prefs.getString("FolderId", null);
        	String imagesAvailable = prefs.getString("ImagesAvailable", null);
	        int imgAvl = Integer.parseInt(imagesAvailable);
			
			if (status) {
				Toast.makeText(CameraActivity.this, CameraActivity.this.getString(R.string.info_image_successfully_saved), Toast.LENGTH_SHORT).show();
				editor.putString("ImagesAvailable", String.valueOf(imgAvl-1));
				editor.commit();
				imgAvl--;
				
				if (imgAvl == 0) {
					try {
						if (previewActive) {
							cam.stopPreview();
							previewActive = false;
						}
						cam.release();
					} catch (Exception e) {
						Log.w(TAG, "in async" + e.toString());
					}
					
					
		        	alertDialog.setTitle(CameraActivity.this.getString(R.string.alert));
		        	TextView tViewWarning = new TextView(CameraActivity.this);
		        	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
		        	tViewWarning.setHeight(90);
		        	alertDialog.setView(tViewWarning);
		        	tViewWarning.setText(CameraActivity.this.getString(R.string.info_max_images_taken));
				    alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							
							try {
							
								if (progressDialog.isShowing()) {
									progressDialog.dismiss();
    							}
				        		Bundle bundle = new Bundle();
				        		bundle.putString(Config.FOLDER_ID, folderId);
								Intent  albumDetailsIntent = new Intent(CameraActivity.this, CameraAlbumDetails.class);
								albumDetailsIntent.putExtras(bundle);
								finish();
								startActivity(albumDetailsIntent);
							} catch (ActivityNotFoundException e) {
								Log.w(TAG, "Unable to start albumDetailsIntent activity: " + e.toString());
							}
							
						}
					});
				    alertDialog.setCancelable(false);
		        	alertDialog.show();
				}
			} else {
	        	alertDialog.setTitle(CameraActivity.this.getString(R.string.warning));
	        	TextView tViewWarning = new TextView(CameraActivity.this);
	        	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
	        	tViewWarning.setHeight(90);
	        	alertDialog.setView(tViewWarning);
	        	tViewWarning.setText(CameraActivity.this.getString(R.string.error_while_saving_image));
			    alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						try {
							Intent MainMenuIntent = new Intent(CameraActivity.this, MainMenuActivity.class);
							finish();
							startActivity(MainMenuIntent);
						} catch (ActivityNotFoundException e) {
							Log.w(TAG, "Error starting MainMenu Activity:" + e.toString());
						}
					}
				});
			    alertDialog.setCancelable(false);
	        	alertDialog.show();
			}
			surfaceView.setOnTouchListener(CameraActivity.this);
			Log.w(TAG, "onPostExecute");
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
				imageSaveRunning = false;
			}
			try {
				cam.startPreview();
			} catch (Exception e) {
				Log.w(TAG, "Error Starting camera in async: " + e.toString());
			}
			imageSaveRunning = false;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			Log.w(TAG, "onPreExecute");
			
		}
		
		
	}
	
	private void startCamera() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
		String imagesAvailable = prefs.getString("ImagesAvailable", null);
	    int imgAvl = Integer.parseInt(imagesAvailable);
	        
       if (imgAvl == 0) {
	       	alertDialog.setTitle(CameraActivity.this.getString(R.string.alert));
	       	TextView tViewWarning = new TextView(CameraActivity.this);
	       	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
	       	tViewWarning.setHeight(90);
	       	alertDialog.setView(tViewWarning);
	       	tViewWarning.setText(CameraActivity.this.getString(R.string.info_max_images_taken));
			    alertDialog.setPositiveButton(CameraActivity.this.getString(R.string.okay), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						try {
							
							if (progressDialog.isShowing()) {
								progressDialog.dismiss();
							}
			        		Bundle bundle = new Bundle();
			        		bundle.putString(Config.FOLDER_ID, folderId);
							Intent  albumDetailsIntent = new Intent(CameraActivity.this, CameraAlbumDetails.class);
							albumDetailsIntent.putExtras(bundle);
							finish();
							startActivity(albumDetailsIntent);
						} catch (ActivityNotFoundException e) {
							Log.w(TAG, "Unable to start albumDetailsIntent activity: " + e.toString());
						}
					}
				});
			alertDialog.setCancelable(false);
	       	alertDialog.show();
       } else {
    	   try {
    			deviceCamera = Camera.open();
    			Parameters parameters = deviceCamera.getParameters();
    	   		supportedPreviewSizes = parameters.getSupportedPreviewSizes();
    	   } catch (Exception e) {
    		   Log.w(TAG, "startCamera: " + e.toString());
    	   }
       
   		
       }
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int id = v.getId();
		
		switch (id) {
		case R.id.svCamera:
			surfaceView.setOnTouchListener(null);
			AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		    int streamType = AudioManager.STREAM_SYSTEM;
		    mgr.setStreamSolo(streamType, true);
		    mgr.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		    mgr.setStreamMute(streamType, true);
			deviceCamera.takePicture(null, null, pictureCallback);
			break;
		}
		return false;
	}
	
}
	

	
	